<template>
  <view class="nearshop-page">
    <!-- 搜索栏 -->
    <view class="search-section">
      <nut-searchbar 
        v-model="searchValue" 
        placeholder="搜索医疗机构" 
        @update:model-value="searchAgency()"
      >
        <template #leftout>
          <span class="text-base text-gray" @click="switchCity()">
            {{ currentCity }}
          </span>
          <view class="i-local-drop-down w-16px h-16px" @click="switchCity()"></view>
        </template>
        <template #rightout>
          <nut-button type="default" size="small" @click="searchAgency()">搜索</nut-button>
        </template>
      </nut-searchbar>
    </view>

    <!-- 空数据状态 -->
    <nut-empty v-if="data?.length == 0" description="暂无数据"></nut-empty>

    <!-- 医疗机构列表 -->
    <view v-for="item in data" :key="item.id" class="hospital-item">
      <view 
        class="hospital-card"
        @click="switchAgency(item.id, item.name, item)"
      >
        <view class="hospital-content">
          <view class="hospital-info">
            <view class="hospital-avatar">
              <nut-avatar size="large">
                <img :src="useImage(item.logo)" />
              </nut-avatar>
            </view>
            <view class="hospital-details">
              <view class="hospital-name">
                <view class="font-bold">{{ item.name }}</view>
              </view>
              <view class="hospital-location">
                <view class="i-local-location w-14px h-14px" />
                <view class="address-text">
                  <nut-ellipsis direction="end" :content="item.address" />
                </view>
                <text 
                  v-if="latitude != -999" 
                  class="distance-text" 
                  @click.stop="trace(latitude, longitude, item.latitude, item.longitude)"
                >
                  {{ item.distance = calculateDistance(latitude, longitude, item.latitude, item.longitude, 2) + 'km' }}
                </text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 城市选择器 -->
    <CitySelector 
      v-model:visible="citySelectorVisible"
      @switch-city="handleCitySwitch"
    />
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useNurseUser, use_hospital_dept_bed } from '../services/HospitalService';
import { useImage } from '@/hooks';
import Taro from '@tarojs/taro';
import { calculateDistance } from '../utils/LocationUtils';
import { localStg } from '../utils/PlatformUtils';
import CitySelector from './CitySelector.vue';
import { EventManager, EVENT_NAMES } from '../utils/EventManager';

// 定义页面配置
definePageConfig({
  navigationBarTitleText: '选择医疗机构'
});

// 响应式数据
const data = ref<any[]>([]);
const data_old = ref<any[]>([]);
const searchValue = ref('');
const latitude = ref(-999);
const longitude = ref(-999);
const currentCity = ref('南宁市');
const citySelectorVisible = ref(false);

// 服务
const { editDefaultHospital } = useNurseUser();
const { getHospitalListByArea } = use_hospital_dept_bed();

// 生命周期
onMounted(() => {
  getLocation();
  getData();
});

// 获取数据
async function getData() {
  Taro.showLoading({ title: '正在请求数据...' });

  const { error, success } = await getHospitalListByArea(currentCity.value);
  if (!error && success) {
    data.value = success;
    data_old.value = success;
    
    // 渠道限制
    if (localStg.get('qudaoid')) {
      const sys_org_code = localStg.get('sys_org_code');
      if (sys_org_code && sys_org_code.length > 6) {
        const str = sys_org_code.substring(0, 6);
        data.value = data.value.filter((item: any) => item.sysOrgCode == str);
      }
    }
  }

  Taro.hideLoading();
}

// 切换机构
async function switchAgency(defaultHospital: any, defaultHospitalName: any, item: any) {
  // console.error("点点滴滴")
  Taro.showLoading({ title: '正在切换机构...' });
  
  try {
    // 更新医院信息到缓存
    Taro.setStorageSync('defaultHospital', JSON.stringify(item));
    
    // 发送医院发生变化事件
    // EventManager.emit(EVENT_NAMES.HOSPITAL_CHANGE, item);
    // EventManager.emit(EVENT_NAMES.SYS_ORG_CHANGE, {
    //   sysOrgCode: item.sysOrgCode,
    //   hospitalId: item.id,
    //   hospitalName: item.name
    // });
    
    // 更新用户默认医院
    const { error } = await editDefaultHospital({ 
      userId: 'current_user_id', 
      defaultHospital, 
      defaultHospitalName 
    });

    // console.log("##### 切换了", error)
    
    if (!error) {
      // 通知父页面
      // const pages = Taro.getCurrentPages();
      // const current = pages[pages.length - 1];
      // const eventChannel = current.getOpenerEventChannel();
      // eventChannel?.emit('switchNearShop', {
      //   data: { defaultHospitalName, distance: item.distance }
      // });
      
      Taro.showToast({
        title: '切换成功',
        icon: 'success',
        duration: 1200
      });
      
      setTimeout(() => {
        // Taro.navigateBack();
        // console.log("重新刷新 😂")
        Taro.reLaunch({url: "/pages/index/index"})
      }, 1200);
    }
  } catch (error) {
    // console.error('切换机构失败:', error);
    Taro.showToast({
      title: '切换失败',
      icon: 'none',
      duration: 1200
    });
  } finally {
    Taro.hideLoading();
  }
}

// 搜索机构
function searchAgency() {
  if (!searchValue.value) searchValue.value = '';
  data.value = data_old.value;
  data.value = data.value.filter((item: any) => item.name.includes(searchValue.value));
}

// 切换城市
function switchCity() {
  citySelectorVisible.value = true;
}

// 处理城市切换
function handleCitySwitch(city: string) {
  currentCity.value = city;
  getData();
  citySelectorVisible.value = false;
}

// 获取用户当前位置
function getLocation() {
  try {
    Taro.getLocation({
      type: 'wgs84',
      needFullAccuracy: true,
      success(res) {
        latitude.value = res.latitude;
        longitude.value = res.longitude;
      }
    });
  } catch (err) {
    Taro.showModal({
      title: '提示',
      content: '获取位置服务信息失败!',
      showCancel: false
    });
  }
}

// 导航到指定位置
function trace(latitude: number, longitude: number, itemLatitude: number, itemLongitude: number) {
  // 导航功能实现
  // console.log('导航到:', itemLatitude, itemLongitude);
}
</script>

<style lang="scss" scoped>
.nearshop-page {
  width: 100%;
  background-color: #f5f5f5;
  min-height: 100vh;
  padding: 20rpx;
}

.search-section {
  margin-bottom: 20rpx;
}

.hospital-item {
  margin-bottom: 16rpx;
}

.hospital-card {
  background: #fff;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  padding: 20rpx;
}

.hospital-content {
  width: 100%;
}

.hospital-info {
  display: flex;
  align-items: center;
  width: 100%;
}

.hospital-avatar {
  margin-right: 16rpx;
}

.hospital-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.hospital-name {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8rpx;
}

.hospital-location {
  display: flex;
  align-items: center;
  font-size: 24rpx;
  color: #666;
  margin-top: 8rpx;
}

.address-text {
  width: 360rpx;
  margin-left: 8rpx;
}

.distance-text {
  margin-left: 16rpx;
  color: #3b82f6;
}

.font-bold {
  font-weight: bold;
}

.text-base {
  font-size: 28rpx;
}

.text-gray {
  color: #666;
}

.w-16px {
  width: 32rpx;
}

.h-16px {
  height: 32rpx;
}

.w-14px {
  width: 28rpx;
}

.h-14px {
  height: 28rpx;
}
</style>
